package com.common.sms.instance;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import com.common.sms.exception.SmsBaseException;
import com.common.sms.config.SmsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author 牧鱼
 * @Classname SmsInstance
 * @Description TODO
 * @Date 2021/5/5
 */
@Component
public class SmsInstance {

    private static final Logger log = LoggerFactory.getLogger(SmsInstance.class);

    /**
     * 依赖注入短信配置
     */
    private SmsConfig smsConfig;

    /**
     * 实例化短信对象
     */
    private Client client;

    public SmsInstance(SmsConfig smsConfig) {
        log.info("初始化短信服务开始");
        long startTime = System.currentTimeMillis();
        this.smsConfig = smsConfig;
        try {
            this.client = initClient();
            log.info("初始化短信成功：{"+smsConfig.getSignName()+"}");
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmsBaseException(e.getMessage());
        }
        log.info("初始化短信服务结束：耗时：{"+(System.currentTimeMillis()-startTime)+"}MS");
    }

    /**
     * 初始化短信对象
     * @return
     * @throws Exception
     */
    private Client initClient() throws Exception{
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(this.smsConfig.getAccessKeyId())
                // 您的AccessKey Secret
                .setAccessKeySecret(this.smsConfig.getAccessKeySecret());
        // 访问的域名
        config.endpoint = this.smsConfig.getEndpoint();
        return new Client(config);
    }

    public Client getSmsClient() {
        return client;
    }

}
